<?php namespace Admin\Controller; 
use Common\Model\Goods;
use Common\Model\GoodsAttr;
use Common\Model\GoodsDetail;
use Common\Model\Cate;
use Common\Model\Brand;
use Common\Model\TypeAttr;
//Goods类控制器
class GoodsController extends CommonController{
	//实例化Model中的Goods类
	private $model;
	public function __auto(){
		$this->model = new Goods;
	}
	
	//显示列表
	public function index(){
	
	
		$data = $this->model->get();
		View::with('data',$data);
		View::make();
	}
	
	//添加
	public function add(){
		if(IS_POST){
			//调用模型文件里的Goods类的store方法
			if($this->model->store()){		
				//若模型类中数据验证正确，成功
				View::success('商品添加成功',U('Goods/index'));	
			}
			//提示错误
			View::error($this->model->getError());	
		}		
		/*1.显示旧数据*/
		//选择分类
		$cateModel = new Cate;
		$cateData = $cateModel->get();
		$cateData = Data::tree($cateData,'cname','cid','pid');
		View::with('cateData',$cateData);
		//品牌选择
		$brandModel = new Brand;
		$brandData = $brandModel->get();
		View::with('brandData',$brandData);

		View::make();
	}

	//异步获得类型属性
	public function getAttr(){
		//异步获取tid
	   	$tid = q('post.t',null,'intval');	
		//关联类型属性	  type_attr表
	   	$typeAttrModel = new typeAttr;
	   	$data = $typeAttrModel->where('type_tid',$tid)->get();
		//把type_attr表的value值改成数组形式，用于传递给js
	  	foreach($data as $k=>$v){
	   		//把字符串变为数组，将来好循环
	   		$data[$k]['value'] = explode('|', $v['value']);
	   	}	
	   	echo json_encode($data);exit;
	}
	
	
  	//uploadify异步上传
	public function upload(){
	    $file = Upload::path('Upload/Content/' . date('y/m'))->make();
	    if (empty($file)) {
	        // 相当于：echo json_encode(Upload::getError());exit;
	        $this->ajax(Upload::getError());
	    }
	    else{
	        /** $file内部就是以下这个数组
	            $file = array(
	                0 => array(
		                'path' => 'Upload/Content/15/8/123981239172.jpg',
		                'url' =>'http://localhost/cms_edu/Upload/Content/15/8/ 123981239172.jpg',
		                'image' => 1
	            ),
	        );**/
	        //上传成功，把上传好的信息返给js 也就是uploadify
	        $data = $file[0];
	        // 相当于：echo json_encode($data);exit;
	        $this->ajax($data);
	    }
	}
	
	//修改
	public function edit(){
		/*2.执行添加*/
		if(IS_POST){
			//调用模型文件里的Type类的store方法去执行数据添加
			if($this->model->edit()){
				//若模型类中数据验证正确，成功
				View::success('修改成功',U('Goods/index'));
			}
			//提示错误
			View::error($this->model->getError());
		}	
		/*1.显示旧数据*/
		$gid = q('get.gid',null,'intval');	
		//关联cate表
		$oldData = Db::table('goods g')
			->join('cate c','g.cate_cid','=','c.cid')
			->join('brand b','g.brand_bid','=','b.bid')
			->join('goods_detail gd','g.gid','=','goods_gid')
			->where("gid={$gid}")
			->first();
		//图片 id变成数组，便于循环	
		$oldData['picture'] = explode('|', $oldData['picture']);		
		View::with('oldData',$oldData);

		//品牌选择
		$brandModel = new Brand;
		$brandData = $brandModel->get();
		View::with('brandData',$brandData);

		//选择分类	页面：基本属性=>所属分类*****************************************************
		$cateModel = new Cate;
		$cateData = $cateModel->get();
		$cateData = Data::tree($cateData,'cname','cid','pid');
		View::with('cateData',$cateData);
		
		//商品属性表
		$goodsData = Db::table('goods_attr ga')
			->join('type_attr ta','ga.type_attr_trid','=','ta.trid')
			->where("goods_gid={$gid}")
			->get();						
		//typeAttr['value']	此处取得是$goodsData['value']，目的为了能进行数组重组
		//接收表里已经有的trid	
		$trid = [];
		foreach($goodsData as $k=>$v){
			//判断value是否有值
			if($v['value']){
				//把type_attr表字符串变为数组，将来好循环
	   			$goodsData[$k]['value'] = explode('|', $v['value']);
				//获得trid就是为了以后排除已经选过的类型属性
				$trid[] = $v['trid'];								
			}   		
	   	}	
		
		//属性类型表
		$typeAttrModel = new TypeAttr;
		$tridStr = implode(',',$trid);
		//把商品没有选过属性也拿取出来
		$tridData = $typeAttrModel->where("trid NOT IN ({$tridStr}) AND type_tid={$oldData['type_tid']}")->get();

		//把未选过的属性追加到$goodsData里
		foreach($tridData as $v){
			$goodsData[] = [
				'gvalue'=>'',
				'trid'=>$v['trid'],
				'trname'=>$v['trname'],
				'value'=>explode('|',$v['value']),
				'class'=>$v['class'],
				'type_tid'=>$v['type_tid'],	
						
			];
		}
//		p($goodsData);
	
		View::with('goodsData',$goodsData);	
		/*	
		 * 方法二：
		 * 重组数组
		 * 目的：把商品属性表的['value']替换成上面 typeAttr['value']，将来好循环
		 * 
			foreach($typeAttr_value as $k=>$v){			
				$DetailData[$k] = [
					'gaid'=>$goodsData[$k]['gaid'],
					'gvalue'=>$goodsData[$k]['gvalue'],
					'add_price'=>$goodsData[$k]['add_price'],
					'type_attr_trid'=>$goodsData[$k]['type_attr_trid'],
					'trname'=>$goodsData[$k]['trname'],
					'value'=>$typeAttr_value[$k],
					'class'=>$goodsData[$k]['class'],
					'type_tid'=>$goodsData[$k]['type_tid'],
				];									
			}
			View::with('DetailData',$DetailData);
		*/					
		
		View::make();
	}
	
	//异步图片删除
	public function delImg(){
		//异步获取图片路径
		$path = q('post.path');
		unlink($path);
	}

	//删除
	public function del(){
		//获取当前要删除的元素
		$gid = q('get.gid',null,'intval');
		//1.删除商品表
		$this->model->where('gid',$gid)->delete();
		//2.删除商品详细表
		$goodsDetail = new GoodsDetail;
		$goodsDetail->where('goods_gid',$gid)->delete();
		//3.删除商品属性表
		$goodsAttr = new GoodsAttr;
		$goodsAttr->where('goods_gid',$gid)->delete();
		View::success('商品删除成功',U('Goods/index'));
	}
	
	//获取tid传给TypeAttr控制器
	public function type(){
		//获取要添加属性的tid
		$gid = q('get.gid',null,'intval');		
		$_SESSION['info']['gid'] =$gid;
		go(U('GoodsList/index'));
	}

}
